package com.example.demoapp.ui;

import androidx.lifecycle.LiveData;
import androidx.lifecycle.MutableLiveData;
import androidx.lifecycle.ViewModel;

import com.example.demoapp.utils.Event;
import com.example.domain.entity.Post;
import com.example.domain.result.Result;
import com.example.domain.usecase.GetAllUserUseCase;
import com.example.domain.usecase.GetUserByIdUseCase;
import com.orhanobut.logger.Logger;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutorService;

import javax.inject.Inject;

import dagger.hilt.android.lifecycle.HiltViewModel;

@HiltViewModel
public class MainActivityViewModel extends ViewModel {

    private GetAllUserUseCase getAllUserUseCase;
    private GetUserByIdUseCase getUserByIdUseCase;
    private ExecutorService executorService;

    private MutableLiveData<List<Post>> _posts = new MutableLiveData<>(Collections.emptyList());
    public LiveData<List<Post>> posts = _posts;

    private MutableLiveData<Boolean> _refreshState = new MutableLiveData<>(false);
    public LiveData<Boolean> refreshState = _refreshState;

    private MutableLiveData<Event<String>> _errorMsg = new MutableLiveData<>();
    public LiveData<Event<String>> errorMsg = _errorMsg;


    @Inject
    public MainActivityViewModel(GetAllUserUseCase getAllUserUseCase,
                                 GetUserByIdUseCase getUserByIdUseCase,
                                 ExecutorService executorService) {
        this.getAllUserUseCase = getAllUserUseCase;
        this.getUserByIdUseCase = getUserByIdUseCase;
        this.executorService = executorService;
    }

    public void refresh() {
        executorService.execute(() -> {
            _refreshState.postValue(true);
            Result<List<Post>> postsResult = getAllUserUseCase.execute(null);
            _refreshState.postValue(false);
            if (postsResult.isSuccess()) {
                Logger.d("post result is success, data is %s", postsResult.getData());
                _posts.postValue(postsResult.getDataWhenSuccess());
            } else {
                _errorMsg.postValue(Event.create(postsResult.getErrorMsgWhenError()));
            }
        });
    }

}
